import React, { useContext, useEffect, useState } from 'react';
import { Link, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { ToastContainer, Toast } from 'react-bootstrap';
import api from './api/api';
import DataContext from './context/DataContext';

const Login = () => {

  const { setIsLoggedIn, setLoginUserId } = useContext(DataContext);
  const history = useHistory();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');

  const handleLogin = async () => {
    try {
      const formData = new FormData();
      formData.append('grant_type', 'password');
      formData.append('username', username);
      formData.append('password', password);

      const response = await api.post('/token', formData, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      const { access_token } = response.data;
      // 将 JWT Token 存储到本地存储中
      localStorage.setItem('token', access_token);
      setToastContent('登录成功!');

      const meResponse = await api.get("/users/me");
      const returnedMe = meResponse.data;

      localStorage.setItem('loginUserId', returnedMe.id); // 存储 loginUserId
      setLoginUserId(returnedMe.id); // 更新上下文中的 loginUserId
      localStorage.setItem('isLoggedIn', false);
      setIsLoggedIn(true);

      setTimeout(() => {
        history.push(`users/${returnedMe.id}`);
      }, 1000);
    } catch (error) {
      setToastContent('登录失败。请检查用户名和密码。');
    } finally {
      setToastShow(true);
    }
  };

  useEffect(() => {
    setIsLoggedIn(false);
    setLoginUserId(false);
  }, [setIsLoggedIn, setLoginUserId]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>登录</h1>
        <form onSubmit={(e) => e.preventDefault()}>
          <div className="mb-3">
            <label for="username" className="form-label">用户名</label>
            <input type="text" className="form-control" id="username" onChange={(e) => { setUsername(e.target.value); }} />
            <div id="Help" className="form-text">如果您还未拥有账号，请先<Link to="/signup">注册</Link>。</div>
          </div>
          <div className="mb-3">
            <label for="password" className="form-label">密码</label>
            <input type="password" className="form-control" id="password" onChange={(e) => { setPassword(e.target.value); }} />
          </div>
          <div className="text-center">
            <button type="submit" className="btn btn-primary" onClick={handleLogin}>提交</button>
          </div>
        </form>
      </div>
      <ToastContainer position='bottom-end' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default Login;
